<?php

namespace app\web\home;


use app\web\model\User as UserModel;
use app\web\model\RechargeStrategy;
use app\web\model\Shop;
use app\web\model\Technician;
use app\web\model\UserBalance;
use app\web\model\UserIntegral;
use app\web\model\Follow;
use app\web\model\Config;
use Yansongda\Pay\Pay;
use app\lib\model\Price;
use app\lib\model\Tool;
use EasyWeChat\Factory;
use app\lib\model\FaceID;

class User extends Base 
{
    /**
     * 实名认证 姓名身份证号码
     * [checkRealNameAuth description]
     * @return [type] [description]
     */
    public function checkRealNameAuth()
    {
        $post = input('post.');
        $model = new FaceID(config('api.TENCENT_SECRET_ID'),config('api.TENCENT_SECRET_KEY'));
        $res = $model->checkIdCardVerification($post['real_name'],$post['id_card']);
        if($res){
            // $t = Technician::get($this->getCurrentId());
            // $t->save($post);
            return show(200,'ok');
        } 
        return show(400,'实名认证失败');
    }
    /**
     * 修改用户信息
     * [add description]
     */
	public function add()
    {
		$post = input('post.');
		if(!empty($post['longitude']) && !empty($post['latitude']) && $this->appkey == 0){
            $res = Tool::coordinateToAddress($post['latitude'],$post['longitude']);
            if($res){
                $post['province'] = $res['address_component']['province'];
                $post['city'] = $res['address_component']['city'];
                $post['area'] = $res['address_component']['district'];
                $post['address'] = $res['formatted_addresses']['rough'];
            }
        }
        if($this->appkey == 0){
            $user = UserModel::get($this->uid);
        }elseif($this->appkey == 1){
            $user = Technician::where(['user_id'=>$this->uid])->find();
        }else{
            $user = Shop::where(['user_id'=>$this->uid])->find();
        }
		$res = $user->save($post);
		if($res){
			return show(200,'数据保存成功');
		}
		return show(400,'数据保存失败');
	}

	
	/**
	 * 个人信息
	 * [info description]
	 * @return [type] [description]
	 */
	public function info(){
		$info = UserModel::where('id',$this->uid)->field('id,nickName,avatarUrl,mobile,balance,integral,gender,wx_code,withdrawal_balance,shop_id,technician_id,province,city,area,address,p_id')->find()->toArray();
        $info['follow_number'] = Follow::where(['user_id'=>$this->uid])->count('id');
        $info['total_revenue'] = UserBalance::where(['user_id'=>$this->uid,'balance_type'=>3,'status'=>1])->sum('change_balance');
		return show(200,'我的信息',$info);
	}

    public function withdrawal($money)
    {
        $info = UserModel::where('id',$this->uid)->field('id,withdrawal_balance')->find()->toArray();
        if(bccomp($money,$info['withdrawal_balance'],2) == 1) return show(400,'可提现余额不足');
        if(bccomp(0,$money,2) != -1) return show(400,'提现金额不能是负数');
        $res = UserBalance::create([
            'user_id' => $this->uid,
            'balance_type' => 4,
            'before_balance' => 0,
            'change_balance' => -$money,
            'after_balance' => 0,
            'status' => 0,
            'appkey' => Config::getAppKey(),
            'notes' => '提现申请'
        ]);
        if($res->isEmpty()) return show(400,'提交失败');
        return show(200,'提交成功');
    }

    /**
     * 积分记录
     * [integralList description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
    public function integralList($status = 0)
    {
        $where[] = ['user_id','=',$this->uid];
        if($status == 0){
            $where[] = ['change_integral','>',0];
        }else{
            $where[] = ['change_integral','<',0]; 
        }
        $list = UserIntegral::where($where)
                    ->field('id,create_time,integral_type,change_integral,status')
                    ->order('id desc')
                    ->paginate();
        return show(200,'积分记录',$list);
    }

    public function balanceList($status = 0)
    {
        $where[] = ['a.user_id','=',$this->uid];
        $where[] = ['a.appkey','=',Config::getAppKey()];
        if($status == 1){
            $where[] = ['a.balance_type','=',3];
        }elseif($status == 2){
            $where[] = ['a.balance_type','=',4];
        }
        $list = UserBalance::alias('a')
                            ->where($where)
                            ->leftjoin('user b','b.id=a.user_id')
                            ->field('a.id,a.balance_type,a.change_balance,a.notes,a.status,a.create_time,b.nickName,b.avatarUrl')
                            ->order('a.id desc')
                            ->paginate();
        return show(200,'余额记录',$list);
    }
    /**
     * 充值策略
     * [rechargeStrategy description]
     * @return [type] [description]
     */
    public function rechargeStrategy(){
        $list = RechargeStrategy::where('status',1)
                    ->field('id,strategy_name,recharge_money,give_money')
                    ->order('recharge_money')
                    ->all();
        return show(200,'充值策略',$list);
    }
    public function balance(){
        $list = UserBalance::alias('a')
                            ->where(['user_id'=>$this->uid,'balance_type'=>0])
                            ->leftjoin('user b','b.id=a.user_id')
                            ->field('a.id,a.change_balance,a.notes')
                            ->order('a.id desc')
                            ->paginate();
        return show(200,'充值记录',$list);
    }
    /**
     * 充值
     * [addBalance description]
     * @param [type] $strategy_id [description]
     */
    public function addBalance($id){
        $list = RechargeStrategy::get($id);
        $user = UserModel::get($this->uid);
        $orderData = [
            'out_trade_no' => $this->getOrderNo(),
            'body' => '会员充值',
            'total_fee' => Price::priceyuantofen($list['recharge_money']),
            'openid' => $this->client == 1 ? $user['openid1'] : $user['openid'],
            'trade_type' => 'JSAPI',
            'attach' => json_encode(['charge_id' => $id, 'user_id' => $this->uid,'client'=>$this->client]),
        ];
        $config = Config::getWechatConfig();
        $config['notify_url'] = $config['recharge'];
        try {
            $result = Pay::wechat($config)->mp($orderData);
            return show(200, "支付接口参数", $result);
        } catch (\Exception $e) {
            return show(500, "支付接口异常".$e->getMessage());
        }
    }

   
    public function myShare($status = 0)
    {
        $where[] = ['p_id','=',$this->uid];
        $where[] = ['nickName','<>',''];
        if($status == 1){
            $where[] = ['shop_id','>',0];
        }elseif ($status == 2) {
            $where[] = ['technician_id','>',0];
        }
        $list = UserModel::where($where)
                        ->field('id,nickName,avatarUrl,create_time')
                        ->order('id desc')
                        ->paginate();
        return show(200,'下级用戶',$list);
    }



    /**
     * 小程序码
     * [getQrCode description]
     * @return [type] [description]
     */
    public function getQrCode()
    {
        $user = UserModel::get($this->uid);
        if($this->appkey == 0){
            $invitation_code = UserModel::getInvitationCode($this->uid);
            $file_path = md5('appcode'.$this->uid).'.png';
            if(is_file('../public/qrcode/'.$file_path)){
                return show(200,'小程序码',[
                    'qrcode' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'].'/qrcode/'.$file_path,
                    'invitation_code' => $invitation_code
                ]);
            }
            $config = Config::getWechatConfig();
            $app = Factory::miniProgram($config);
            $response = $app->app_code->get('/pages/index/index?user_id='.$this->uid,  []);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs('qrcode', $file_path);
                return show(200,'小程序码',[
                    'qrcode'=>$_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'].'/qrcode/'.$filename,
                    'invitation_code' => $invitation_code
                ]);
            }
        }elseif($this->appkey == 2){
            if($this->auth_status != 0){
                return show(400,'无权添加管理员');
            }
            $auth_status = input('auth_status',0);
            $shop_id = $this->getCurrentId();
            $file_path = md5('shop_appcode'.$shop_id.'auth'.$auth_status).'.png';
            if(is_file('../public/qrcode/'.$file_path)){
                return show(200,'小程序码',[
                    'qrcode' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'].'/qrcode/'.$file_path,
                ]);
            }
            $config = Config::getWechatConfig();
            $app = Factory::miniProgram($config);
            $response = $app->app_code->get('/pages/index/index?shop_id='.$shop_id.'&auth_status='.$auth_status.'&time='.time(),  []);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs('qrcode', $file_path);
                return show(200,'小程序码',[
                    'qrcode'=>$_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'].'/qrcode/'.$filename,
                ]);
            }
        }
        
        return show(400,'小程序码获取失败');

    }
    /**
     * 解密手机号
     * @return \think\response\Json
     */
    public function decrypt_mobile(){

        try {
            $app = Factory::miniProgram(Config::getWechatConfig());
            $session = $app->auth->session(input('param.code'));
            $session_key = $session['session_key'];
            $iv = input('param.iv');
            $encryptedData = input('param.encryptedData');
            $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
        }catch (\Exception $e){
            return show(500,$e->getMessage());
        }
        if(empty($decryptedData['phoneNumber'])){
            return show(500,'手机号获取失败');
        }
        $res = UserModel::where('id',$this->uid)->update(['mobile'=>$decryptedData['phoneNumber']]);
        if($res !== false){
            return show(200,'手机号码',$decryptedData['phoneNumber']);
        }
        return show(500,'手机号保存失败'); 
    }








    /**
     * 人脸识别
     * [faceToFace description]
     * @return [type] [description]
     */
    public function faceToFace()
    {
        $post = input('post.');
        $user = UserModel::get($this->uid);
        // $t_data = Technician::get($this->getCurrentId());
        $model = new FaceID(config('api.TENCENT_SECRET_ID'),config('api.TENCENT_SECRET_KEY'));
        if(!empty($post['avatarUrl'])){
            $res = $model->deletePerson($user);
            $user->rerson_id = '';
            $user->save();
            // $t_data['avatarUrl'] = $post['avatarUrl'];
            // $t_data->save();
        }
        $res = $model->faceToFace($user,$post);
        if($res === false) return show(400,'识别失败');
        return show(200,'识别成功',$res);
    }
}